package cn.lxsir.uniapp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.lxsir.uniapp.common.Constants;
import cn.lxsir.uniapp.dto.UserDto;
import cn.lxsir.uniapp.entity.User;
import cn.lxsir.uniapp.exception.ServiceException;
import cn.lxsir.uniapp.mapper.UserMapper;
import cn.lxsir.uniapp.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author luoxiang
 * @since 2019-07-13
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Override
    public UserDto login(UserDto userDto) {
        User one=getUserInfo(userDto);
        if( one != null){
            BeanUtil.copyProperties(one,userDto,true);
            return userDto;
        }else{
            throw new ServiceException(Constants.CODE_600,"用户名或密码错误");
        }
    }

    private User getUserInfo(UserDto userDTO){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone",userDTO.getPhone());
        queryWrapper.eq("password",userDTO.getPassword());
        User user =null;
        try {
            user=getOne(queryWrapper);
        }catch (Exception e){
            e.printStackTrace();
        }
        return user;
    }

    @Override
    public User register(UserDto userDTO) {
        User one=getUserInfo(userDTO);
        if( one == null){
            one = new User();
            BeanUtil.copyProperties(userDTO,one,true);
            one.setIntegral("0");
            save(one);
        }
        return one;
    }
}
